package com.zm.zmgz.service;

import com.zm.zmgz.dao.ProjectProfitBeanMapper;
import com.zm.zmgz.pojo.*;
import com.zm.zmgz.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: cjw
 * @Date: 2020/05/13/11:13
 * @Description:
 */
@Service
public class ProjectProfitService {

    @Autowired
    ProjectProfitBeanMapper projectProfitBeanMapper;

    @Autowired
    SalarySettlementService salarySettlementService;

    @Autowired
    EmployeeService employeeService;


    /***
     * @Description: 通过日期刷新该批次的项目盈利数据
     * 判断是否存在该批次
     *  存在:删除该批次数据
     * 重新创建该批次
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 11:14:25
     */
    @Transactional
    public boolean refreshProjectProfit(Date date) {
        int i = 0;
        // 判断是否存在该批次;存在:删除该批次数据
        if (!isExsitCurrentBatchByDate(date))
            deleteBatchByDate(date);
        i += addBatchByDate(date);
        return i == 0 ? false : true;
    }

    /***
     * @Description: 判断传入日期内是否存在批次
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 11:25:51
     */
    public boolean isExsitCurrentBatchByDate(Date date2) {
        Date date = new Date();
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        ProjectProfitBeanExample projectProfitBeanExample = new ProjectProfitBeanExample();
        ProjectProfitBeanExample.Criteria criteria = projectProfitBeanExample.createCriteria();
        criteria.andCreationdateBetween(monthStart, monthEnd);
        List<ProjectProfitBean> projectProfitBeans = projectProfitBeanMapper.selectByExample(projectProfitBeanExample);

        return false;
    }

    /***
     * @Description: 根据传入日期, 删除日期内批次
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 12:17:34
     */
    @Transactional
    public int deleteBatchByDate(Date date) {
        int i = 0;
        List<ProjectProfitBean> batchByDate = getBatchByDate(date, 0, 0);
        if (Objects.isNull(batchByDate) || batchByDate.size() == 0)
            return 0;
        for (ProjectProfitBean profitBean : batchByDate) {
            i += projectProfitBeanMapper.deleteByPrimaryKey(profitBean.getId());
        }
        return i;
    }

    /***
     * @Description: 根据传入日期, 获取日期内批次数据
     * 排序:项目名降序,税前工资降序
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 12:17:34
     */
    public List<ProjectProfitBean> getBatchByDate(Date date, Integer page, Integer limit) {
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        ProjectProfitBeanExample projectProfitBeanExample = new ProjectProfitBeanExample();
        ProjectProfitBeanExample.Criteria criteria = projectProfitBeanExample.createCriteria();
        criteria.andCreationdateBetween(monthStart, monthEnd);
        projectProfitBeanExample.setOrderByClause("itemName desc, preTaxWages desc");
        List<ProjectProfitBean> projectProfitBeans = projectProfitBeanMapper.selectByExample(projectProfitBeanExample);
        // 假分页
        if (!Objects.isNull(projectProfitBeans) && projectProfitBeans.size() > 0) {
            Integer total = projectProfitBeans.size();
            if (page != 0 && limit != 0) {
                projectProfitBeans = (List<ProjectProfitBean>) CollectionUtilszm.getListPagination(projectProfitBeans, page, limit);
            }
            projectProfitBeans.get(0).setTotal(total);
            return projectProfitBeans;
        } else
            return null;
    }

    /***
     * @Description: 根据传入日期, 创建该批次(创建前先手动删除该日期内批次)
     * 创建项目盈利对象集合
     * 日期+发放状态获取工资结算对象集合
     * 遍历工资结算对象集合
     *  创建工资结算对象
     *  通过工资结算对象获取员工对象
     *  通过员工对象和工资结算对象填充项目盈利对象
     * 将项目盈利对象集合添加到数据库中
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-13 12:17:34
     */
    @Transactional
    public int addBatchByDate(Date date) {
        // 创建项目盈利对象集合
        List<ProjectProfitBean> list = new ArrayList<>();
        // 日期+发放状态获取工资结算对象集合
        List<SalarySettlementDetailsBean> detailsBeans = salarySettlementService.getSalarySettlementListByTimeLimitAndStatus(date, "已发放");
        // 遍历工资结算对象集合;创建工资结算对象;通过工资结算对象获取员工对象;通过员工对象和工资结算对象填充项目盈利对象
        if (!Objects.isNull(detailsBeans) && detailsBeans.size() > 0) {
            for (SalarySettlementDetailsBean detailsBean : detailsBeans) {
                ProjectProfitBean profitBean = new ProjectProfitBean();
                EmployeeBean employeeBean = employeeService.getEmployeeByIdentificationnumber(detailsBean.getIdentificationnumber());
                profitBean.setEnterprisespayfiveinsurancesandonegold(BigDecimalUtils.add(detailsBean.getCorporatesocialsecurity(), detailsBean.getEnterprisespayprovidentfund()));
                profitBean.setItemname(detailsBean.getProjectname());
                profitBean.setCreationdate(date);
                // 通过身份证获取姓名
                String identificationnumber = detailsBean.getIdentificationnumber();
                EmployeeBean employeeBean1 = employeeService.getEmployeeByIdentificationnumber(identificationnumber);
                profitBean.setPostname(employeeBean1.getPostname());
                profitBean.setName(employeeBean1.getName());
                profitBean.setIdcard(detailsBean.getIdentificationnumber());
                profitBean.setPosettlementfee(employeeBean.getPosettlementfee());
                profitBean.setTaxrate(employeeBean.getPotaxrate());

                if (!Objects.isNull(detailsBean.getTaxablesalary())) {
                    profitBean.setPretaxwages(detailsBean.getTaxablesalary().toString());
                }
                // po结费
                double a = Double.parseDouble(ObjectsUtils.nullToZero(profitBean.getPosettlementfee()).toString());
                // po税
                double b = 1 - StringCjwUtils.getDoubleByPercent(ObjectsUtils.nullToZero(profitBean.getTaxrate()).toString());
                // 税前工资
                double c = BigDecimalUtils.nullToZero(detailsBean.getTaxablesalary()).doubleValue();
                // 企业五险一金
                double d = BigDecimalUtils.nullToZero(BigDecimalUtils.add(detailsBean.getCorporatesocialsecurity(), detailsBean.getEnterprisespayprovidentfund())).doubleValue();
                profitBean.setProfit(DoubleUtils.getRoundToTwoDecimalPlaces(a * b - c - d) + "");
                list.add(profitBean);
            }
        }
        int i = 0;
        for (ProjectProfitBean profitBean : list) {
            i += projectProfitBeanMapper.insert(profitBean);
        }
        return i;
    }


    /***
     * @Description:返回该月项目盈利统计记录,key为项目名,value为数额
     * 获取该月项目盈利记录集合
     * 创建map
     * 遍历集合
     * 无key则创建并赋值
     * 存在key则累加
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-14 12:18:51
     */
    public Map<String, Double> getProProfitStatistics(Date date) {
        // 获取该月项目盈利记录集合
        List<ProjectProfitBean> list = getBatchByDate(date, 0, 0);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        // 创建map;遍历集合;无key则创建并赋值;存在key则累加
        Map<String, Double> map = new HashMap<>();
        for (ProjectProfitBean profitBean : list) {
            String itemname = profitBean.getItemname();
            if (map.containsKey(itemname))
                map.replace(itemname, map.get(itemname) + Double.parseDouble(profitBean.getProfit()));
            else
                map.put(itemname, Double.parseDouble(profitBean.getProfit()));
        }
        return map;
    }


    /***
     * @Description: 获取该批次所有项目名
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-18 00:56:40
     */
    public List<String> getItemNamesByDate(Date date) {
        List<ProjectProfitBean> list = getBatchByDate(date, 0, 0);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        List<String> list1 = new ArrayList<>();
        for (ProjectProfitBean profitBean : list) {
            if (!list1.contains(profitBean.getItemname()))
                list1.add(profitBean.getItemname());
        }
        return list1;
    }

    /***
     * @Description: 通过批次和项目获取名记录
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-18 01:05:07
     */
    public List<ProjectProfitBean> getBatchByDateAndItemName(Date date, String s) {
        ProjectProfitBeanExample projectProfitBeanExample = new ProjectProfitBeanExample();
        ProjectProfitBeanExample.Criteria criteria = projectProfitBeanExample.createCriteria();
        Date monthStart = DateUtils.getMonthStart(date);
        Date monthEnd = DateUtils.getMonthEnd(date);
        criteria.andCreationdateBetween(monthStart, monthEnd).andItemnameEqualTo(s);
        return projectProfitBeanMapper.selectByExample(projectProfitBeanExample);
    }


    /***
     * @Description: 获取批次选择数据
     * - 获取全部记录(排序:批次升序,项目名升序,利润降序;creationDate ASC, itemName asc,profit DESC)
     * - 遍历全部记录，创建数据对象集合
     *   - 获取时间，提取年，年级中是否存在该年
     *     - 有则提取月，判断月级中是否存在该月
     *       - 有则舍弃（看你是否要日级）
     *       - 无则创建该月级
     *     - 无则创建该年级
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-21 21:36:15
     */
    public List<ProjectProfitBatchOptionBean> getBatchOptions() {
        // 获取全部记录(排序:批次升序,项目名升序,利润降序;creationDate ASC, itemName asc,profit DESC)
        String order = "creationDate ASC, itemName ASC,profit DESC";
        List<ProjectProfitBean> list = getAllAndOrder(order);
        if (Objects.isNull(list) || list.size() == 0)
            return null;
        // 遍历全部记录，创建数据对象集合,进行解析
        List<ProjectProfitBatchOptionBean> list1 = new ArrayList<>();
        for (ProjectProfitBean profitBean : list) {
            Date date = profitBean.getCreationdate();
            String year = DateUtils.getDateString(date, "YYYY年");
            String month = DateUtils.getDateString(date, "MM月");
            // 搜索是否存在该年;如果不存在就添加该年该月
            int i = 0;
            for (ProjectProfitBatchOptionBean bean : list1) {
                // 该年存在
                if (bean.getValue().equals(year)) {
                    // 搜索是否存在该月
                    List<ProjectProfitBatchOptionBean> list2 = bean.getChildren();
                    int j = 0;
                    // 遍历该年是否存在该月
                    for (ProjectProfitBatchOptionBean optionBean : list2) {
                        if (optionBean.getLabel().equals(month)) {
                            j++;
                            break;
                        }
                    }
                    // 该年存在,但该月不存在,添加月
                    if (j == 0) {
                        ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                        optionBean1.setValue(year + month);
                        optionBean1.setLabel(month);
                        bean.getChildren().add(optionBean1);
                    }
                    i++;
                    break;
                }
            }
            // 该年不存在
            if (i == 0) {
                ProjectProfitBatchOptionBean optionBean = new ProjectProfitBatchOptionBean();
                optionBean.setLabel(year);
                optionBean.setValue(year);
                optionBean.setChildren(new ArrayList<>());
                ProjectProfitBatchOptionBean optionBean1 = new ProjectProfitBatchOptionBean();
                optionBean1.setValue(year + month);
                optionBean1.setLabel(month);
                optionBean.getChildren().add(optionBean1);
                list1.add(optionBean);
            }

        }
        return list1;
    }

    /***
     * @Description: 获取全部数据并按要求排序
     * @Param:
     * @return:
     * @Author: cjw
     * @Date: 2020-05-22 03:00:35
     */
    private List<ProjectProfitBean> getAllAndOrder(String order) {
        ProjectProfitBeanExample projectProfitBeanExample = new ProjectProfitBeanExample();
        projectProfitBeanExample.setOrderByClause(order);
        List<ProjectProfitBean> list = projectProfitBeanMapper.selectByExample(projectProfitBeanExample);
        return list;
    }


    /***
    * @Description:判断员工是否在试用期
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-05-28 08:48:12
    */
    public Boolean isProbationByProfitBean(ProjectProfitBean profitBean) {
        return employeeService.isProbationByIdCard(profitBean.getIdcard());
    }

    /***
    * @Description: 判断员工是否在转正
    * @Param:
    * @return:
    * @Author: cjw
    * @Date: 2020-05-28 08:59:18
    */
    public Boolean isFormalByProfitBean(ProjectProfitBean profitBean) {
        return employeeService.isFormalByIdCard(profitBean.getIdcard());
    }
}
